package com.zjw.zy.coreui.view

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import com.zjw.zy.R
import com.zjw.zy.base.BaseViewGroup
import com.zjw.zy.ext.edit
import com.zjw.zy.ext.ignoreKeyBoard
import com.zjw.zy.ext.normal

class SearchView : BaseViewGroup {

    private val mSearchText: EditText by lazy { findViewById(R.id.search_view_edit) }
    private val mClear: ImageView by lazy { findViewById(R.id.search_view_clear) }

    private var mListener: OnSearchListener? = null

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
    }

    override fun onLayoutId(): Int {
        return R.layout.search_view_layout
    }

    override fun onBindListener() {
        mSearchText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                s.toString().let {
                    mListener?.onSearchTextChange(it)
                    if (it.isEmpty()) {
                        mClear.visibility = View.GONE
                    } else {
                        mClear.visibility = View.VISIBLE
                    }
                }

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        mClear.setOnClickListener {
            mSearchText.setText("")
        }
    }

    override fun onBindValue() {
        mClear.ignoreKeyBoard()
    }

    override fun onFindView(rootView: View) {}

    fun bindListener(listener: OnSearchListener) {
        mListener = listener
    }

    interface OnSearchListener {
        fun onSearchTextChange(keyword: String)
    }
}